package com.mbc.rmt.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

import com.mbc.common.CommonSingleton;
import com.mbc.common.dao.CommonDAOFactory;
import com.mbc.common.dao.CurrencyRateDAO;
import com.mbc.common.dao.LogDAO;
import com.mbc.common.entities.CurrencyRate;
import com.mbc.common.entities.Log;
import com.mbc.common.exception.DataNotFoundException;
import com.mbc.common.manager.AbstractMgr;
import com.mbc.common.utils.KeyGenerator;
import com.mbc.rmt.dao.AgentBalanceDAO;
import com.mbc.rmt.dao.AgentCOADAO;
import com.mbc.rmt.dao.AgentDAO;
import com.mbc.rmt.dao.BankDAO;
import com.mbc.rmt.dao.CashReturnDAO;
import com.mbc.rmt.dao.CashReturnDetailDAO;
import com.mbc.rmt.dao.General_COADAO;
import com.mbc.rmt.dao.OfficeCOADAO;
import com.mbc.rmt.dao.RemittanceDAOFactory;
import com.mbc.rmt.dao.SentCOADAO;
import com.mbc.rmt.dao.TypeDAO;
import com.mbc.rmt.dao.WaitingCOADAO;
import com.mbc.rmt.data.CashReturnDataList;
import com.mbc.rmt.entities.Agent;
import com.mbc.rmt.entities.AgentBalance;
import com.mbc.rmt.entities.AgentCOA;
import com.mbc.rmt.entities.Bank;
import com.mbc.rmt.entities.CashReturn;
import com.mbc.rmt.entities.CashReturnDetails;
import com.mbc.rmt.entities.CashReturnRpt;
import com.mbc.rmt.entities.GeneralLedger;
import com.mbc.rmt.entities.General_COA;
import com.mbc.rmt.entities.OfficeCOA;
import com.mbc.rmt.entities.SentCOA;
import com.mbc.rmt.entities.Type;
import com.mbc.rmt.entities.WaitingCOA;

public class CashReturnMgr extends AbstractMgr {

	private CashReturnDAO cashReturnDAO;
	private CashReturnDetailDAO cashReturnDetailDAO;
	private TypeDAO typeDAO;
	private AgentBalanceDAO agentbalanceDAO;
	private CurrencyRateDAO currencyRateDAO;
	private AgentCOADAO agentCOADAO;
	private AgentDAO agentDAO;
	private BankDAO bankDAO;
	private General_COADAO generalCOADAO;
	private OfficeCOADAO officeCOADAO;
	private WaitingCOADAO waitingCOADAO;
	private SentCOADAO sentCOADAO;
	private LogDAO logDAO;

	public static enum GL_STATUS {
		CREATE, DELETE
	}

	public static final byte IN = 1;
	public static final byte OUT = 0;

	public CashReturnMgr(String sessionId) {
		this.sessionId = sessionId;
	}

	public String create(CashReturn entity) throws Exception {
		openConnection();
		try {
			cashReturnDAO = RemittanceDAOFactory
					.getCashReturnDAO(getConnection());
			cashReturnDetailDAO = RemittanceDAOFactory
					.getCashReturnDetailDAO(getConnection());
			typeDAO = RemittanceDAOFactory
					.getTypeDAO(dbManager.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager
					.getConnection());

			beginTransaction();

			// Go To AgentBalance
			if (entity.getTrtype() == 1) {
				for (CashReturnDetails l_detail : entity.getL_details()) {
					AgentBalance l_agent = new AgentBalance();
					l_agent.setAgent_id(entity.getAgentid());
					l_agent.setCurrencyid(l_detail.getCurrencyid());
					l_agent = agentbalanceDAO.getInfo(l_agent);
					if (l_agent == null) {
						l_agent = new AgentBalance();
						l_agent.setAgentbalance_id(KeyGenerator
								.generateKey(getConnection()));
						l_agent.setAgent_id(entity.getAgentid());
						l_agent.setCurrencyid(l_detail.getCurrencyid());
						l_agent.setCurrentbalance(-l_detail.getAmount());
						agentbalanceDAO.create(l_agent);
					} else {
						l_agent.setCurrentbalance(l_agent.getCurrentbalance()
								- l_detail.getAmount());
						agentbalanceDAO.update(l_agent);
					}
				}
			}
			// End Go To AgentBalance

			String voucher = "";
			entity.setSlipid(KeyGenerator.generateKey(getConnection()));
			if (entity.getTrtype() == 1)
				voucher = RemittanceSerialMgr.getFormattedSerial(
						RemittanceSerialMgr.CASH_RETURN_BY_AGENT_N_BANK,
						entity.getTrdate(), entity.getDefaultbranchid(),
						getConnection());
			else if (entity.getTrtype() == 2)
				voucher = RemittanceSerialMgr.getFormattedSerial(
						RemittanceSerialMgr.CASH_RETURN_BY_SENT,
						entity.getTrdate(), entity.getDefaultbranchid(),
						getConnection());
			else if (entity.getTrtype() == 3)
				voucher = RemittanceSerialMgr.getFormattedSerial(
						RemittanceSerialMgr.CASH_RETRUN_BY_OFFICE,
						entity.getTrdate(), entity.getDefaultbranchid(),
						getConnection());
			else
				voucher = RemittanceSerialMgr.getFormattedSerial(
						RemittanceSerialMgr.CASH_RETURN_BY_WAITING,
						entity.getTrdate(), entity.getDefaultbranchid(),
						getConnection());
			
			entity.setSlipno(voucher);

			Type type = new Type();
			if (entity.getTrtype() == 2) {
				entity.setTypecode("S");
				type = typeDAO.findByCode(entity.getTypecode(),
						entity.getDefaultbranchid());
				entity.setTypeid(type.getType_id());
			} else if (entity.getTrtype() == 3) {
				entity.setTypecode("O");
				type = typeDAO.findByCode(entity.getTypecode(),
						entity.getDefaultbranchid());
				entity.setTypeid(type.getType_id());
			} else if (entity.getTrtype() == 4) {
				entity.setTypecode("W");
				type = typeDAO.findByCode(entity.getTypecode(),
						entity.getDefaultbranchid());
				entity.setTypeid(type.getType_id());
			}

			gotoGL(entity, GL_STATUS.CREATE, entity.getTrtype());

			cashReturnDAO.create(entity);
			
			Log l_logentity = new Log();
			l_logentity.setTablename("CashReturn");
			l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
			l_logentity.setUserid(entity.getCreatedby());
			l_logentity.setKey(entity.getSlipid());
			l_logentity.setLogstatus(Log.__SAVE_DATA);
			logDAO.getData(l_logentity);

			if (entity != null) {
				if (entity.getL_details().size() > 0) {
					for (int i = 0; i < entity.getL_details().size(); i++) {
						entity.getL_details().get(i)
								.setSlipid(entity.getSlipid());
						entity.getL_details()
								.get(i)
								.setSlipdetailid(
										KeyGenerator
												.generateKey(getConnection()));
						cashReturnDetailDAO
								.create(entity.getL_details().get(i));

						cashReturnDetailDAO.updateCashPaymentReturnStatus(
								entity.getL_details().get(i)
										.getPaymentdetailid(), entity
										.getL_details().get(i)
										.getDefinedetailid(), entity
										.getL_details().get(i).getAmount(), IN);
						
						l_logentity.setTablename("CashReturnDetails");
						l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
						l_logentity.setKey(entity.getL_details().get(i).getSlipdetailid());
						l_logentity.setLogstatus(Log.__SAVE_DATA);
						logDAO.getData(l_logentity);
					}
				}
			}

			commintTransaction();
			return voucher;
		} catch (Exception e) {
			rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}

	public void update(ArrayList<Long> deletekeys, CashReturn entity)
			throws Exception {
		openConnection();
		try {
			cashReturnDAO = RemittanceDAOFactory
					.getCashReturnDAO(getConnection());
			cashReturnDetailDAO = RemittanceDAOFactory
					.getCashReturnDetailDAO(getConnection());
			agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager
					.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			Log l_logentity = new Log();

			beginTransaction();

			gotoGL(entity, GL_STATUS.CREATE, entity.getTrtype());

			cashReturnDAO.update(entity);
			
			l_logentity.setTablename("CashReturn");
			l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
			l_logentity.setUserid(entity.getModifiedby());
			l_logentity.setKey(entity.getSlipid());
			l_logentity.setLogstatus(Log.__UPDATE_DATA);
			logDAO.getData(l_logentity);

			if (deletekeys != null) {
				if (deletekeys.size() > 0) {
					for (int j = 0; j < deletekeys.size(); j++) {

						CashReturnDetails l_info = cashReturnDetailDAO
								.findById(deletekeys.get(j));

						if (entity.getTrtype() == 1) {
							AgentBalance l_agent = new AgentBalance();
							l_agent.setAgent_id(entity.getAgentid());
							l_agent.setCurrencyid(l_info.getCurrencyid());
							l_agent = agentbalanceDAO.getInfo(l_agent);
							if (l_agent == null) {
								l_agent = new AgentBalance();
								l_agent.setAgentbalance_id(KeyGenerator
										.generateKey(getConnection()));
								l_agent.setAgent_id(entity.getAgentid());
								l_agent.setCurrencyid(l_info.getCurrencyid());
								l_agent.setCurrentbalance(-l_info.getAmount());
								agentbalanceDAO.create(l_agent);
							} else {
								l_agent.setCurrentbalance(l_agent
										.getCurrentbalance()
										- l_info.getAmount());
								agentbalanceDAO.update(l_agent);
							}

						}

						cashReturnDetailDAO.updateCashPaymentReturnStatus(
								l_info.getPaymentdetailid(),
								l_info.getDefinedetailid(), l_info.getAmount(),
								OUT);
						
						l_logentity.setTablename("CashReturnDetails");
						l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
						l_logentity.setKey(entity.getL_details().get(j).getSlipid());
						l_logentity.setLogstatus(Log.__DELETE_DATA);
						logDAO.getData(l_logentity);

						cashReturnDetailDAO.delete(deletekeys.get(j),
								CashReturnDetailDAO.DETAIL);
						
					}
				}
			}

			for (int i = 0; i < entity.getL_details().size(); i++) {

				if (entity.getL_details().get(i).getSlipdetailid() != null)
					cashReturnDetailDAO.update(entity.getL_details().get(i));
				else {

					entity.getL_details().get(i).setSlipid(entity.getSlipid());
					entity.getL_details()
							.get(i)
							.setSlipdetailid(
									KeyGenerator.generateKey(getConnection()));

					if (entity.getTrtype() == 1) {
						for (CashReturnDetails l_detail : entity.getL_details()) {
							AgentBalance l_agent = new AgentBalance();
							l_agent.setAgent_id(entity.getAgentid());
							l_agent.setCurrencyid(l_detail.getCurrencyid());
							l_agent = agentbalanceDAO.getInfo(l_agent);
							if (l_agent == null) {
								l_agent = new AgentBalance();
								l_agent.setAgentbalance_id(KeyGenerator
										.generateKey(getConnection()));
								l_agent.setAgent_id(entity.getAgentid());
								l_agent.setCurrencyid(l_detail.getCurrencyid());
								l_agent.setCurrentbalance(-l_detail.getAmount());
								agentbalanceDAO.create(l_agent);
							} else {
								l_agent.setCurrentbalance(l_agent
										.getCurrentbalance()
										- l_detail.getAmount());
								agentbalanceDAO.update(l_agent);
							}
						}
					}

					cashReturnDetailDAO.create(entity.getL_details().get(i));

					cashReturnDetailDAO.updateCashPaymentReturnStatus(entity
							.getL_details().get(i).getPaymentdetailid(), entity
							.getL_details().get(i).getDefinedetailid(), entity
							.getL_details().get(i).getAmount(), IN);

				}
				
				l_logentity.setTablename("CashReturnDetails");
				l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
				l_logentity.setKey(entity.getL_details().get(i).getSlipdetailid());
				l_logentity.setLogstatus(Log.__UPDATE_DATA);
				logDAO.getData(l_logentity);
			}

			commintTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}

	public void delete(long key,long userid) throws Exception {
		openConnection();
		try {
			cashReturnDAO = RemittanceDAOFactory
					.getCashReturnDAO(getConnection());
			cashReturnDetailDAO = RemittanceDAOFactory
					.getCashReturnDetailDAO(getConnection());
			agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager
					.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			Log l_logentity = new Log();

			beginTransaction();

			// Go To AgentBalance
			CashReturn entity = new CashReturn();
			entity = cashReturnDAO.findById(key);
			if (entity.getTrtype() == 1) {
				ArrayList<CashReturnDetails> detail = cashReturnDetailDAO
						.findByHeaderId(key);
				if (detail != null) {
					for (int i = 0; i < detail.size(); i++) {
						AgentBalance l_agent = new AgentBalance();
						l_agent.setAgent_id(entity.getAgentid());
						l_agent.setCurrencyid(detail.get(i).getCurrencyid());
						l_agent = agentbalanceDAO.getInfo(l_agent);
						if (l_agent != null) {
							l_agent.setAgent_id(entity.getAgentid());
							l_agent.setCurrencyid(detail.get(i).getCurrencyid());
							l_agent.setCurrentbalance(l_agent
									.getCurrentbalance()
									+ detail.get(i).getAmount());
							agentbalanceDAO.update(l_agent);
						}
					}
				}
			}
			// End Go To AgentBalance

			ArrayList<CashReturnDetails> l_detail = cashReturnDetailDAO
					.findByHeaderId(key);
			if (l_detail != null) {
				for (int i = 0; i < l_detail.size(); i++) {
					cashReturnDetailDAO.updateCashPaymentReturnStatus(l_detail
							.get(i).getPaymentdetailid(), l_detail.get(i)
							.getDefinedetailid(), l_detail.get(i).getAmount(),
							OUT);
				}
			}

			gotoGL(entity, GL_STATUS.DELETE, entity.getTrtype());
			
			l_logentity.setTablename("CashReturnDetails");
			l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
			l_logentity.setKey(l_detail.get(0).getSlipdetailid());
			l_logentity.setLogstatus(Log.__DELETE_DATA);
			logDAO.getData(l_logentity);
			
			l_logentity.setTablename("CashReturn");
			l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
			l_logentity.setKey(key);
			l_logentity.setUserid(userid);
			l_logentity.setLogstatus(Log.__DELETE_DATA);
			logDAO.getData(l_logentity);

			cashReturnDetailDAO.delete(key, CashReturnDetailDAO.HEARDER);
			cashReturnDAO.delete(key);

			commintTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}

	public CashReturnDataList getCashReturnList(CashReturn l_cri)
			throws Exception {
		openConnection();
		try {
			cashReturnDAO = RemittanceDAOFactory
					.getCashReturnDAO(getConnection());
			cashReturnDetailDAO = RemittanceDAOFactory
					.getCashReturnDetailDAO(getConnection());

			CashReturnDataList l_dataList = cashReturnDAO
					.findCashReturnByCri(l_cri);

			for (int i = 0; i < l_dataList.getEntityList().size(); i++)
				l_dataList
						.getEntityList()
						.get(i)
						.setL_details(
								cashReturnDetailDAO.findByHeaderId(l_dataList
										.getEntityList().get(i).getSlipid()));

			return l_dataList;
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}

	public void gotoGL(CashReturn l_entity, GL_STATUS status, int temp)
			throws Exception {

		currencyRateDAO = CommonDAOFactory.getCurrencyRateDAO(getConnection());
		agentCOADAO = RemittanceDAOFactory.getAgentCOADAO(getConnection());
		agentDAO = RemittanceDAOFactory.getAgentDAO(getConnection());
		officeCOADAO = RemittanceDAOFactory.getOfficeCOADAO(getConnection());
		waitingCOADAO = RemittanceDAOFactory.getWaitingCOADAO(getConnection());
		sentCOADAO = RemittanceDAOFactory.getSentCOADAO(getConnection());
		generalCOADAO = RemittanceDAOFactory.getGeneral_COADAO(getConnection());
		bankDAO = RemittanceDAOFactory.getBankDAO(getConnection());

		String glSlip = "", glcode = "";
		if (temp == 1) {
			glSlip = l_entity.getSlipno() + "-RA";
			glcode = "JRA";
		} else if (temp == 2) {
			glSlip = l_entity.getSlipno() + "-RS";
			glcode = "JRS";
		} else if (temp == 3) {
			glSlip = l_entity.getSlipno() + "-RO";
			glcode = "JRO";
		} else if (temp == 4) {
			glSlip = l_entity.getSlipno() + "-RW";
			glcode = "JRW";
		}

		GeneralLedgerMgr l_glmgr = new GeneralLedgerMgr(this.sessionId);
		l_glmgr.deleteGL(glSlip);

		if (status == GL_STATUS.CREATE) {
			GeneralLedger _glHeader = new GeneralLedger();
			_glHeader.setGlKey(l_glmgr.getGLKey());
			_glHeader.setSlip_ID(glSlip);
			_glHeader.setSlipDate(l_entity.getTrdate());
			_glHeader.setSystemDate(new Date());
			_glHeader.setStatus("JH");
			_glHeader.setSrNo(1);
			_glHeader.setOffice_ID(l_entity.getDefaultbranchid());

			l_glmgr.createGL(_glHeader);

			for (int i = 0; i < l_entity.getL_details().size(); i++) {

				CurrencyRate l_currencyrate = currencyRateDAO.getCurrencyRateFromSourcetoHome(l_entity.getL_details().get(i).getCurrencyid(), l_entity.getDefaultbranchid());

				if (l_entity.getBankid() == null) {
					General_COA l_generalCOA = generalCOADAO.find(l_entity.getDefaultbranchid());

					if (l_generalCOA == null)
						throw new DataNotFoundException("Plz fill general coa",General_COA.class);

					GeneralLedger _glHeaderGeneral = new GeneralLedger();
					_glHeaderGeneral.setGlKey(l_glmgr.getGLKey());
					_glHeaderGeneral.setSlip_ID(glSlip);
					_glHeaderGeneral.setSlipDate(l_entity.getTrdate());
					_glHeaderGeneral.setSystemDate(new Date());
					_glHeaderGeneral.setStatus(glcode);
					_glHeaderGeneral.setSrNo(2);
					_glHeaderGeneral.setOffice_ID(l_entity.getDefaultbranchid());
					_glHeaderGeneral.setCoaKey(l_generalCOA.getCashAccountID());
					_glHeaderGeneral.setDepartmentKey(l_generalCOA.getCashDepartmentID());
					_glHeaderGeneral.setCurrencyKey(l_entity.getL_details().get(i).getCurrencyid());
					_glHeaderGeneral.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
					_glHeaderGeneral.setExchangeRate(l_currencyrate.getRate());
					_glHeaderGeneral.setSourceAmount(l_entity.getL_details().get(i).getAmount());

					if (l_currencyrate.getRoper().equals("M"))
						_glHeaderGeneral.setHomeAmount(l_entity.getL_details().get(i).getAmount() * l_currencyrate.getRate());
					else
						_glHeaderGeneral.setHomeAmount(l_entity.getL_details().get(i).getAmount() / l_currencyrate.getRate());

					l_glmgr.createGL(_glHeaderGeneral);
				} else {
					Bank l_bank = bankDAO.find(l_entity.getBankid());
					if (l_bank != null) {
						GeneralLedger _glHeaderBank = new GeneralLedger();
						_glHeaderBank.setGlKey(l_glmgr.getGLKey());
						_glHeaderBank.setSlip_ID(glSlip);
						_glHeaderBank.setSlipDate(l_entity.getTrdate());
						_glHeaderBank.setSystemDate(new Date());
						_glHeaderBank.setStatus(glcode);
						_glHeaderBank.setSrNo(2);
						_glHeaderBank.setOffice_ID(l_entity.getDefaultbranchid());
						_glHeaderBank.setCoaKey(l_bank.getCoaid());
						_glHeaderBank.setDepartmentKey(l_bank.getDepartmentid());
						_glHeaderBank.setCurrencyKey(l_entity.getL_details().get(i).getCurrencyid());
						_glHeaderBank.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glHeaderBank.setExchangeRate(l_currencyrate.getRate());
						_glHeaderBank.setSourceAmount(l_entity.getL_details().get(i).getAmount());

						if (l_currencyrate.getRoper().equals("M"))
							_glHeaderBank.setHomeAmount(l_entity.getL_details().get(i).getAmount() * l_currencyrate.getRate());
						else
							_glHeaderBank.setHomeAmount(l_entity.getL_details().get(i).getAmount() / l_currencyrate.getRate());

						l_glmgr.createGL(_glHeaderBank);
					}else
						throw new DataNotFoundException("pls fill bank",Bank.class);
				}
					if (temp == 1) { // Cash Return Agent & Bank
						Agent l_agent = agentDAO.findById(l_entity.getAgentid());
						if (l_agent != null) {
							AgentCOA l_agentCOA = agentCOADAO.find(l_agent.getAccountset_id());

							if (l_agentCOA == null)
								throw new DataNotFoundException("Plz fill AgentCOA",AgentCOA.class);

							GeneralLedger _glDebit = new GeneralLedger();
							_glDebit.setGlKey(l_glmgr.getGLKey());
							_glDebit.setSlip_ID(glSlip);
							_glDebit.setSlipDate(l_entity.getTrdate());
							_glDebit.setSystemDate(new Date());
							_glDebit.setCoaKey(l_agentCOA.getAccpayable());
							_glDebit.setDepartmentKey(l_agentCOA.getAccpayable_dept());
							_glDebit.setCurrencyKey(l_entity.getL_details().get(i).getCurrencyid());
							_glDebit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
							_glDebit.setExchangeRate(l_currencyrate.getRate());
							_glDebit.setSourceAmount(-l_entity.getL_details().get(i).getAmount());

							if (l_currencyrate.getRoper().equals("M"))
								_glDebit.setHomeAmount(-(l_entity.getL_details().get(i).getAmount() * l_currencyrate.getRate()));
							else
								_glDebit.setHomeAmount(-(l_entity.getL_details().get(i).getAmount() / l_currencyrate.getRate()));

							_glDebit.setStatus(glcode);
							_glDebit.setSrNo((i + 3));
							_glDebit.setOffice_ID(l_entity.getDefaultbranchid());

							l_glmgr.createGL(_glDebit);
						} else
							throw new DataNotFoundException("");

					} else if (temp == 2) { // Cash Return Sent

						SentCOA l_sentCOA = sentCOADAO.findByCode("S", l_entity.getDefaultbranchid());
						
						if (l_sentCOA != null) {

							GeneralLedger _glDetailCredit = new GeneralLedger();
							_glDetailCredit.setGlKey(l_glmgr.getGLKey());
							_glDetailCredit.setSlip_ID(glSlip);
							_glDetailCredit.setSlipDate(l_entity.getTrdate());
							_glDetailCredit.setSystemDate(new Date());
							_glDetailCredit.setStatus(glcode);
							_glDetailCredit.setSrNo(2);
							_glDetailCredit.setOffice_ID(l_entity.getDefaultbranchid());
							_glDetailCredit.setCoaKey(l_sentCOA.getAccpayable());
							_glDetailCredit.setDepartmentKey(l_sentCOA.getAccpayable_dept());
							_glDetailCredit.setCurrencyKey(l_entity.getL_details().get(i).getCurrencyid());
							_glDetailCredit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
							_glDetailCredit.setExchangeRate(l_currencyrate.getRate());
							_glDetailCredit.setSourceAmount(-l_entity.getL_details().get(i).getAmount());

							if (l_currencyrate.getRoper().equals("M"))
								_glDetailCredit.setHomeAmount(-(l_entity
												.getL_details().get(i)
												.getAmount() * l_currencyrate
												.getRate()));
							else
								_glDetailCredit.setHomeAmount(-(l_entity
												.getL_details().get(i)
												.getAmount() / l_currencyrate
												.getRate()));

							l_glmgr.createGL(_glDetailCredit);

						} else
							throw new DataNotFoundException("Plz fill SentCOA",SentCOA.class);

					} else if (temp == 3) { // Cash Return Office

						OfficeCOA l_officeCOA = officeCOADAO.findByCode("O", l_entity.getDefaultbranchid());
						if (l_officeCOA != null) {

							GeneralLedger _glDetailCredit = new GeneralLedger();
							_glDetailCredit.setGlKey(l_glmgr.getGLKey());
							_glDetailCredit.setSlip_ID(glSlip);
							_glDetailCredit.setSlipDate(l_entity.getTrdate());
							_glDetailCredit.setSystemDate(new Date());
							_glDetailCredit.setStatus(glcode);
							_glDetailCredit.setSrNo(2);
							_glDetailCredit
									.setOffice_ID(l_entity.getDefaultbranchid());
							_glDetailCredit.setCoaKey(l_officeCOA
									.getAccpayable());
							_glDetailCredit.setDepartmentKey(l_officeCOA
									.getAccpayable_dept());
							_glDetailCredit.setCurrencyKey(l_entity.getL_details().get(i).getCurrencyid());
							_glDetailCredit.setCurrencyRateKey(l_currencyrate
									.getCurrencyRateId());
							_glDetailCredit.setExchangeRate(l_currencyrate
									.getRate());
							_glDetailCredit.setSourceAmount(-l_entity
									.getL_details().get(i).getAmount());

							if (l_currencyrate.getRoper().equals("M"))
								_glDetailCredit
										.setHomeAmount(-(l_entity
												.getL_details().get(i)
												.getAmount() * l_currencyrate
												.getRate()));
							else
								_glDetailCredit
										.setHomeAmount(-(l_entity
												.getL_details().get(i)
												.getAmount() / l_currencyrate
												.getRate()));

							l_glmgr.createGL(_glDetailCredit);
						} else
							throw new DataNotFoundException("pls fill officeCOA",OfficeCOA.class);
					} else if (temp == 4) { // Cash Return Waiting

						WaitingCOA l_waitingCOA = waitingCOADAO.findByCode("W", l_entity.getDefaultbranchid());
						
						if (l_waitingCOA != null) {

							GeneralLedger _glDetailCredit = new GeneralLedger();
							_glDetailCredit.setGlKey(l_glmgr.getGLKey());
							_glDetailCredit.setSlip_ID(glSlip);
							_glDetailCredit.setSlipDate(l_entity.getTrdate());
							_glDetailCredit.setSystemDate(new Date());
							_glDetailCredit.setStatus(glcode);
							_glDetailCredit.setSrNo(2);
							_glDetailCredit
									.setOffice_ID(l_entity.getDefaultbranchid());
							_glDetailCredit.setCoaKey(l_waitingCOA
									.getAccpayable());
							_glDetailCredit.setDepartmentKey(l_waitingCOA
									.getAccpayable_dept());
							_glDetailCredit.setCurrencyKey(l_entity.getL_details().get(i).getCurrencyid());
							_glDetailCredit.setCurrencyRateKey(l_currencyrate
									.getCurrencyRateId());
							_glDetailCredit.setExchangeRate(l_currencyrate
									.getRate());
							_glDetailCredit.setSourceAmount(-l_entity
									.getL_details().get(i).getAmount());

							if (l_currencyrate.getRoper().equals("M"))
								_glDetailCredit
										.setHomeAmount(-(l_entity
												.getL_details().get(i)
												.getAmount() * l_currencyrate
												.getRate()));
							else
								_glDetailCredit
										.setHomeAmount(-(l_entity
												.getL_details().get(i)
												.getAmount() / l_currencyrate
												.getRate()));

							l_glmgr.createGL(_glDetailCredit);
						} else
							throw new DataNotFoundException("pls fill waitingCOA",WaitingCOA.class);
					}
				}
			}

	}

	// Report
	public JasperPrint prepareCashReturnReport(CashReturnRpt entity)
			throws Exception {
		openConnection();
		JasperPrint l_jsPrint = null;
		try {
			cashReturnDAO = RemittanceDAOFactory
					.getCashReturnDAO(getConnection());
			JRResultSetDataSource l_jrRS = new JRResultSetDataSource(
					cashReturnDAO.prepareCashReturnReport(entity));
			JasperReport l_jsRpt = null;

			l_jsRpt = (JasperReport) JRLoader
					.loadObjectFromFile(CommonSingleton.ABSOLUTE_PATH
							+ "reports/CashReturn.jasper");
			HashMap<String, Object> l_params = new HashMap<String, Object>();
			l_params.put("company", "mbc");
			l_jsPrint = JasperFillManager.fillReport(l_jsRpt, l_params, l_jrRS);
		} catch (JRException je) {
			throw je;
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
		return l_jsPrint;
	}
}
